import React from 'react';
import _ from 'lodash';
import { dynamicRoute } from '@/../config/routes';
import { findPathFromTree } from '@/utils/utils';
import * as Icon from '@ant-design/icons';

const transitionPaths = _.map(
  _.filter(
    dynamicRoute,
    ({ path, shareWithParamsKey }) => /\/\*$/.test(path) && !shareWithParamsKey,
  ),
  'path',
);

// 格式化路由
export const initRouteMaps = (routeMaps) => {
  const shareOptions = _.map(
    _.filter(dynamicRoute, ({ shareWithParamsKey }) => !!shareWithParamsKey),
    ({ path, shareWithParamsKey }) => ({ path, shareWithParamsKey }),
  );
  const dynamicResPaths = _.map(
    _.filter(dynamicRoute, ({ shareWithParamsKey }) => !shareWithParamsKey),
    'path',
  );
  const formatRoute = (list) => {
    if (list && list.length) {
      _.forEach(list, (item) => {
        item.key = `/${item.id}`;
        item.label = item.title || '';
        item.icon = React.createElement(Icon[item.menuIcon] || Icon['MenuOutlined']);
        if (item.children && item.children.length) {
          formatRoute(item.children);
        } else if (item.routePath) {
          let targetSourceParams;
          try {
            if (item.sourceParams) {
              targetSourceParams = JSON.parse(item.sourceParams);
            }
          } catch (e) {
            console.log('通配页面参数解析异常', e);
          }
          const shareOpt = _.find(shareOptions, ({ shareWithParamsKey }) => {
            const targetPathParams = (targetSourceParams || {})[shareWithParamsKey];
            return _.isString(targetPathParams) && !!targetPathParams;
          });
          if (shareOpt && shareOpt.path === item.routePath) {
            const targetPath =
              item.routePath.replace(/\*$/, '') +
              window.btoa((targetSourceParams || {})[shareOpt.shareWithParamsKey]);
            item.key = targetPath;
            item.path = targetPath;
            delete item.sourceParams;
          } else {
            if (_.includes(dynamicResPaths, item.routePath)) {
              item.path = item.routePath.replace(/\/\*$/, '/default');
              item.key = item.path;
            } else {
              item.path = `/${item.id}`;
            }
          }
        } else {
          item.path = `/${item.id}`;
        }
      });
    }
  };
  formatRoute(routeMaps);
  return routeMaps;
};

// 获取路由路径集合
export const getRoutePath = (tree) => {
  const treeToList = (list = [], ret = []) => {
    for (const item of list) {
      const node = { ...item };
      Reflect.deleteProperty(node, 'children');
      ret.push(node);
      treeToList(item.children || [], ret);
    }
    return ret;
  };
  const menuItems = treeToList(tree);
  return _.filter(_.map(menuItems, 'path'), (item) => !!item);
};

// 获取路由的路径列表及默认url
export const getRouteExtraOptions = (tree) => {
  const ret = {};
  const pathList = getRoutePath(tree);
  const defaultUrl = _.head(pathList) || '';
  _.forEach(pathList, (path) => {
    const routePath = findPathFromTree(tree, (item) => item.path === path);
    if (routePath.length) {
      ret[path] = routePath;
    }
  });
  return { routePathList: ret, defaultUrl };
};

// 通配路由转译
export const getOriginalPath = (path) => {
  for (let i = 0; i < transitionPaths.length; i++) {
    const reg = new RegExp('^' + transitionPaths[i].replace(/\*$/, ''));
    if (reg.test(path)) {
      return transitionPaths[i].replace(/\/\*$/, '/default');
    }
  }
  return path;
};
